package io.itit.ecp.admin.provide.action.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import icu.mhb.mybatisplus.plugln.core.JoinLambdaWrapper;
import icu.mhb.mybatisplus.plugln.extend.Joins;
import io.itit.ecp.admin.provide.action.req.DeviceWarningRecordQueryReq;
import io.itit.ecp.admin.provide.action.resp.DeviceWarningPushUserResp;
import io.itit.ecp.admin.provide.action.resp.DeviceWarningRecordResp;
import io.itit.ecp.admin.provide.helper.SceneHelper;
import io.itit.ecp.admin.server.entity.DeviceWarningPushUserEntity;
import io.itit.ecp.admin.server.entity.DeviceWarningRecordEntity;
import io.itit.ecp.admin.server.entity.SceneProjectEntity;
import io.itit.ecp.admin.server.service.IDeviceWarningPushUserService;
import io.itit.ecp.admin.server.service.IDeviceWarningRecordService;
import io.itit.grass.common.provide.action.req.BaseBatchIdReq;
import io.itit.grass.common.provide.action.req.BaseIdReq;
import io.itit.grass.common.provide.action.resp.ResultResp;
import io.itit.grass.common.provide.action.validation.IQueryPage;
import io.itit.grass.common.provide.action.validation.IRequired;
import io.itit.grass.common.server.utils.ConvertUtils;
import io.itit.grass.web.wall.utils.PageUtils;
import io.itit.grass.web.wall.utils.ShiroUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *
 * @Author：Roy
 * @Description：设备管理-预警管理
 * @Date：Create by 2023-12-04 15:28:53
 */
@Api(tags = "设备管理-预警管理")
@RestController
@RequestMapping("/ecp-admin/deviceWarningRecord")
public class DeviceWarningRecordController {

    @Resource
    private IDeviceWarningRecordService deviceWarningRecordService;

    @Resource
    private IDeviceWarningPushUserService deviceWarningPushUserService;

    @ApiOperation("分页查询")
    @PostMapping("queryPage")
    @RequiresPermissions("ecp-admin:deviceWarningRecord:search")
    public ResultResp<IPage<DeviceWarningRecordResp>> queryPage(@RequestBody @Validated(IQueryPage.class) DeviceWarningRecordQueryReq req) {
        Page<DeviceWarningRecordResp> page = buildQW(req).joinPage(PageUtils.getPage(req, DeviceWarningRecordResp.class), DeviceWarningRecordResp.class);
        return ResultResp.success(SceneHelper.i().setSceneInfo(page));
    }

    @ApiOperation("详情")
    @PostMapping("detail")
    @RequiresPermissions("ecp-admin:deviceWarningRecord:search")
    public ResultResp<DeviceWarningRecordResp> detail(@RequestBody @Validated(IRequired.class) BaseIdReq req) {
        String userId = ShiroUtils.getUserId();
        List<DeviceWarningPushUserEntity> list = deviceWarningPushUserService.findByWarningRecordId(req.getId());
        list.stream().filter(item -> StringUtils.equals(item.getUserId(), userId))
                .findFirst()
                .ifPresent(item -> {
                    if (Objects.isNull(item.getReadDate())) {
                        item.setStatus("2");
                        item.setReadDate(new Date());
                        deviceWarningPushUserService.updateById(item);
                    }
                });
        DeviceWarningRecordEntity recordEntity = deviceWarningRecordService.getById(req.getId());
        if (list.stream().allMatch(item -> StringUtils.equals(item.getStatus(), "2"))) {
            recordEntity.setStatus("3");
        } else if (list.stream().anyMatch(item -> StringUtils.equals(item.getStatus(), "2"))) {
            recordEntity.setStatus("2");
        }
        deviceWarningRecordService.updateById(recordEntity);
        DeviceWarningRecordResp deviceWarningRecordResp = ConvertUtils.copy(recordEntity, DeviceWarningRecordResp.class);
        deviceWarningRecordResp.setWarningPushUsers(list
                .stream().map(item -> {
                    DeviceWarningPushUserResp pushUserResp = new DeviceWarningPushUserResp();
                    pushUserResp.setId(item.getId());
                    pushUserResp.setUserId(item.getUserId());
                    pushUserResp.setUserName(item.getUserName());
                    pushUserResp.setReadDate(item.getReadDate());
                    pushUserResp.setStatus(item.getStatus());
                    return pushUserResp;
                }).collect(Collectors.toList()));
        return ResultResp.success(deviceWarningRecordResp);
    }

    /**
     * 组装查询条件
     */
    private static JoinLambdaWrapper<DeviceWarningRecordEntity> buildQW(DeviceWarningRecordQueryReq req) {
        return Joins.of(DeviceWarningRecordEntity.class)
                .leftJoin(SceneProjectEntity.class, SceneProjectEntity::getId, DeviceWarningRecordEntity::getSceneProjectId)
                .select(SceneProjectEntity::getProjectName)
                .end()
                .like(StringUtils.isNotEmpty(req.getWarningName()), DeviceWarningRecordEntity::getWarningName, req.getWarningName())
                .eq(StringUtils.isNotEmpty(req.getSceneProjectId()), DeviceWarningRecordEntity::getSceneProjectId, req.getSceneProjectId())
                .eq(StringUtils.isNotEmpty(req.getSceneEdificeId()), DeviceWarningRecordEntity::getSceneEdificeId, req.getSceneEdificeId())
                .eq(StringUtils.isNotEmpty(req.getSceneFloorId()), DeviceWarningRecordEntity::getSceneFloorId, req.getSceneFloorId())
                .eq(StringUtils.isNotEmpty(req.getSceneRoomId()), DeviceWarningRecordEntity::getSceneRoomId, req.getSceneRoomId())
                .in(CollectionUtils.isNotEmpty(req.getIds()), DeviceWarningRecordEntity::getId, req.getIds())
                .like(StringUtils.isNotEmpty(req.getDeviceId()), DeviceWarningRecordEntity::getDeviceDetails, req.getDeviceId())
                .like(StringUtils.isNotEmpty(req.getDeviceName()), DeviceWarningRecordEntity::getDeviceDetails, req.getDeviceName())
                .ge(Objects.nonNull(req.getWarningDate()), DeviceWarningRecordEntity::getWarningDate, req.getWarningDate())
                .last(StringUtils.isNotEmpty(req.getSortColumn()), PageUtils.lastOrderBy(req))
                .orderByDesc(StringUtils.isEmpty(req.getSortColumn()), DeviceWarningRecordEntity::getCreateTm);
    }

    @ApiOperation("删除(根据Id删)")
    @PostMapping("deleteById")
    @RequiresPermissions("ecp-admin:deviceWarningRecord:deleteById")
    public ResultResp<Boolean> deleteById(@RequestBody @Validated({IRequired.class}) BaseIdReq req) {
        return ResultResp.success(deviceWarningRecordService.removeById(req.getId()));
    }

    @ApiOperation("批量删除")
    @PostMapping("batchDelete")
    @RequiresPermissions("ecp-admin:deviceWarningRecord:batchDelete")
    public ResultResp<Boolean> batchDelete(@RequestBody @Validated({IRequired.class}) BaseBatchIdReq req) {
        return ResultResp.success(deviceWarningRecordService.removeBatchByIds(req.getIds(), 1000));
    }
}
